package com.luyuan.crm.member.service.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import com.luyuan.crm.member.model.Region;
import com.luyuan.crm.member.service.RegionService;
import com.ruijie.foundation.dao.support.HibernateEntityDao;
import com.ruijie.util.StringUtils;

public class RegionServiceImpl extends HibernateEntityDao<Region> implements RegionService {

    @SuppressWarnings("unchecked")
    @Override
    public List<Region> loadProvince() {
        return createCriteria(Restrictions.isNull("city"), Restrictions.isNull("region")).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Region> loadCity(String province) {
        return createCriteria(Restrictions.eq("province", province), Restrictions.isNull("region")).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Region> loadRegion(String province, String city) {
        return createCriteria(Restrictions.eq("province", province), Restrictions.eq("city", city)).list();
    }

    @Override
    public Region getByRegion(String province, String city, String region) {
        if (StringUtils.isNullOrEmpty(province) || StringUtils.isNullOrEmpty(city)) {
            return null;
        }

        Criteria criteria = createCriteria(Restrictions.eq("province", province), Restrictions.eq("city", city));
        if (StringUtils.isNullOrEmpty(region)) {
            criteria.add(Restrictions.isNull("region"));
        }
        else {
            criteria.add(Restrictions.eq("region", region));
        }
        return (Region) criteria.uniqueResult();
    }

    @Override
    public Region findProvincialCapital(String province, String city) {
        if (StringUtils.isNotEmpty(province)) {
            return (Region) createCriteria(Restrictions.eq("province", province), Restrictions.isNull("city"),
                    Restrictions.isNull("region")).uniqueResult();
        }

        return (Region) createCriteria(Restrictions.like("city", city + "%")).setMaxResults(1).uniqueResult();
    }
}
